package com.example.shardingjdbc.utils;

import lombok.extern.slf4j.Slf4j;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Description: 日期工具类
 * @Author: Jerry
 * @Date: 2021-08-02 23:15
 */
@Slf4j
public class DateUtils {

    /**
     * 年月日正则
     */
    public static final SimpleDateFormat YMD_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 根据月份返回月份对应的季度
     * @param month 月份，比如1月对应数字1
     * @return 季度，比如一季度对应数字1
     */
    public static int getQuarterFromMonth(int month) {
        switch (month) {
            case 1:
            case 2:
            case 3:
                return 1;
            case 4:
            case 5:
            case 6:
                return 2;
            case 7:
            case 8:
            case 9:
                return 3;
            case 10:
            case 11:
            case 12:
                return 4;
            default:
                return 0;
        }
    }

    /**
     * 根据起止时间产生随机日期
     * @param startDate 开始时间字符串，比如"2019-01-01","2019-01-31"
     * @param endDate 结束时间字符串，比如"2019-01-01","2019-01-31"
     * @return 在startDate和endDate之间的随机日期
     */
    public static Date getRandomDate(String startDate, String endDate) {
        Date res = new Date();
        try {
            Date start = YMD_FORMAT.parse(startDate);
            Date end = YMD_FORMAT.parse(endDate);

            if (start.getTime() >= end.getTime()) {
                log.error("getRandomDate error, start time is after end time");
                return null;
            }

            long dateTime = randomDate(start.getTime(),end.getTime());
            res = new Date(dateTime);
        } catch (ParseException e) {
            log.error("getRandomDate error, exception is {}", (Object) e.getStackTrace());
        }

        return res;
    }

    private static long randomDate(long begin,long end){
        long rtn = begin + (long)(Math.random() * (end - begin));
        if(rtn == begin || rtn == end){
            return randomDate(begin,end);
        }
        return rtn;
    }
}
